package com.cskaoyan.market.service.Impl;

import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.db.domain.MarketUserExample;
import com.cskaoyan.market.db.mapper.MarketUserMapper;
import com.cskaoyan.market.service.MarketStatService;
import com.cskaoyan.market.vo.MarketStatVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 付诚
 * @Date: 2024/5/20 14:13
 * @Description:
 */
@Service
public class MarketStatServiceImpl implements MarketStatService {

    @Autowired
    private MarketUserMapper marketUserMapper;
    @Override
    public Map<String, List<Object>> user() {

        Map<String, List<Object>> data = new HashMap<>();
        ArrayList<Object> columns = new ArrayList<>();
        columns.add("day");
        columns.add("users");

        List<Object> rows;
        List<MarketUser> marketUserList = marketUserMapper.selectByExample(new MarketUserExample());

        rows = groupByDay(marketUserList);
        data.put("columns", columns);
        data.put("rows", rows);


        return data;
    }

    private List<Object> groupByDay(List<MarketUser> marketUserList) {


        List<Object> rows = new ArrayList<>();

        Map<String, Integer> statGroupByDay = new HashMap<>();
        for (MarketUser marketUser : marketUserList) {


            LocalDateTime addTime = marketUser.getAddTime();
            String day = addTime.toString().substring(0, 10);

            Integer user = statGroupByDay.get(day);
            if (user == null) {
                user = 0;
            }
            user++;
            statGroupByDay.put(day, user);
        }

        for (Map.Entry<String, Integer> entry : statGroupByDay.entrySet()) {
            MarketStatVo marketStatVo = new MarketStatVo(entry.getKey(), entry.getValue());
            rows.add(marketStatVo);
        }
        return rows;

    }
}
